from CvPythonExtensions import *
from WriterUtils import *

import CvScreenEnums
import CvUtil
import CvConfigParser
import CvPath
import os
import os.path
import Popup as PyPopup
import shutil 

# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
localText = CyTranslator()

# Change this to change the location where the resulting CIV4BuildInfos.xml file 
# will be saved. So if the default value is left to "Test" then the 
# CIV4BuildInfos.xml file would be written in a directory called "Test" inside 
# of the Tech Tree Editor mod folder.
# Default value is Test
g_strSaveDirectoryLocation = "Test"

# Change the value to false if the assets directory structure shouldn't be 
# created at the directory specified by the "Save Directory Location".
# Default value is True
g_bCreateAssetHierarchy = True

# Change the value to false if the changes made shouldn't be saved into the 
# assets directory for the tech editor. Changing it to false will require 
# manual copying of the saved files from the directory specified in the 
# "Save Directory Location" configurable option to the editor's asset directory 
# when wanting to edit existing mod files.
# Default value is True
g_bSaveChangesInEditorAssetsDirectory = True

def loadConfigurationValues():
	global g_strSaveDirectoryLocation
	global g_bCreateAssetHierarchy
	global g_bSaveChangesInEditorAssetsDirectory
	
	config = CvConfigParser.CvConfigParser("ViSa_v3.ini")

	if(config != None):
		g_strSaveDirectoryLocation = config.get("Tech Tree Editor", "Save Directory Location", "Test")
		g_bCreateAssetHierarchy = config.getboolean("Tech Tree Editor", "Create Asset Hierarchy", True)
		g_bSaveChangesInEditorAssetsDirectory = config.getboolean("Tech Tree Editor", "Save Changes In Editor Assets Directory", True)

		if(len(g_strSaveDirectoryLocation) == 0):
			g_strSaveDirectoryLocation = "Test"
			
class BuildInfoWriter:
		
	def __init__(self):
		loadConfigurationValues()

	def featureStructDefined(self, iBuild):
		objBuildInfo = gc.getBuildInfo(iBuild)

		for iI in range(gc.getNumFeatureInfos()):
			if(objBuildInfo.getFeatureTime(iI) != 0):
				return true
		return false

	def printBuild(self, iBuild):
		objBuildInfo = gc.getBuildInfo(iBuild)

		szText = ""
		
		szText = appendString(szText,"		<BuildInfo>")
		
		szText = appendString(szText,"			<Type>%s</Type>" %(objBuildInfo.getType()))


		szText = appendString(szText,"			<Description>%s</Description>" %(objBuildInfo.getTextKey()))

		if(len(objBuildInfo.getHelpKey()) > 0):
			szText = appendString(szText,"			<Help>%s</Help>" %(objBuildInfo.getHelpKey()))
		else:
			szText = appendString(szText,"			<Help/>")

		if(objBuildInfo.getTechPrereq() != -1):
			szText = appendString(szText,"			<PrereqTech>%s</PrereqTech>" %(gc.getTechInfo(objBuildInfo.getTechPrereq()).getType()))
		else:
			szText = appendString(szText,"			<PrereqTech>NONE</PrereqTech>")

		szText = appendString(szText,"			<iTime>%s</iTime>" %(objBuildInfo.getTime()))
		szText = appendString(szText,"			<bKill>%s</bKill>" %(boolToInt(objBuildInfo.isKill())))

		if(objBuildInfo.getImprovement() != -1):
			szText = appendString(szText,"			<ImprovementType>%s</ImprovementType>" %(gc.getImprovementInfo(objBuildInfo.getImprovement()).getType()))
		else:
			szText = appendString(szText,"			<ImprovementType>NONE</ImprovementType>")

		if(objBuildInfo.getRoute() != -1):
			szText = appendString(szText,"			<RouteType>%s</RouteType>" %(gc.getRouteInfo(objBuildInfo.getRoute()).getType()))
		else:
			szText = appendString(szText,"			<RouteType>NONE</RouteType>")
		
		if(objBuildInfo.getEntityEvent() != -1):
			szText = appendString(szText,"			<EntityEvent>%s</EntityEvent>" %(gc.getEntityEventInfo(objBuildInfo.getEntityEvent()).getType()))
		else:
			szText = appendString(szText,"			<EntityEvent>NONE</EntityEvent>")
		
		if(self.featureStructDefined(iBuild)):
			szText = appendString(szText,"			<FeatureStructs>")
			for iI in range(gc.getNumFeatureInfos()):
				if(objBuildInfo.getFeatureTime(iI) != 0):
					szText = appendString(szText,"				<FeatureStruct>")
					szText = appendString(szText,"					<FeatureType>%s</FeatureType>" %(gc.getFeatureInfo(iI).getType()))
					if(objBuildInfo.getFeatureTech(iI) != -1):
						szText = appendString(szText,"					<PrereqTech>%s</PrereqTech>" %(gc.getTechInfo(objBuildInfo.getFeatureTech(iI)).getType()))
					else:
						szText = appendString(szText,"					<PrereqTech>NONE</PrereqTech>")

					szText = appendString(szText,"					<iTime>%s</iTime>" %(objBuildInfo.getFeatureTime(iI)))
					szText = appendString(szText,"					<iProduction>%s</iProduction>" %(objBuildInfo.getFeatureProduction(iI)))
					szText = appendString(szText,"					<bRemove>%s</bRemove>" %(boolToInt(objBuildInfo.isFeatureRemove(iI))))
					szText = appendString(szText,"				</FeatureStruct>")

			szText = appendString(szText,"			</FeatureStructs>")
		else:
			szText = appendString(szText,"			<FeatureStructs/>")


		if(len(objBuildInfo.getHotKey()) > 0):
			szText = appendString(szText,"			<HotKey>%s</HotKey>" %(objBuildInfo.getHotKey()))
		else:
			szText = appendString(szText,"			<HotKey/>")
		
		szText = appendString(szText,"			<bAltDown>%s</bAltDown>" %(boolToInt(objBuildInfo.isAltDown())))
		szText = appendString(szText,"			<bShiftDown>%s</bShiftDown>" %(boolToInt(objBuildInfo.isShiftDown())))
		szText = appendString(szText,"			<bCtrlDown>%s</bCtrlDown>" %(boolToInt(objBuildInfo.isCtrlDown())))
		szText = appendString(szText,"			<iHotKeyPriority>%s</iHotKeyPriority>" %(objBuildInfo.getHotKeyPriority()))
		if(objBuildInfo.getOrderPriority() != 5):
			szText = appendString(szText,"			<iOrderPriority>%s</iOrderPriority>" %(objBuildInfo.getOrderPriority()))

		szText = appendString(szText,"			<Button>%s</Button>" %(objBuildInfo.getButton()))

		szText = appendString(szText,"		</BuildInfo>")
			
		return szText

						
	def printBuilds(self):	
	
		strSavePath = ""
		strFileSavePath = ""
		strModPath = ""
		strModAssetPath = ""
		strModAssetSavePath = ""
		strModAssetPath = ""
		
		if(os.access(CvPath.userActiveModDir,os.F_OK)):
			strModPath = CvPath.userActiveModDir
		elif(os.access(CvPath.installActiveModDir,os.F_OK)):
			strModPath = CvPath.installActiveModDir
		else:
			self.dataSavePopup(false)
			return
			
		strSavePath = "%s\%s" %(strModPath,g_strSaveDirectoryLocation)
		strModAssetPath = "%s\\Assets\\" %(strModPath)
		
		if(g_bCreateAssetHierarchy):
			strSavePath += "\Assets\XML\Units" 

		strFileSavePath = "%s\%s" %(strSavePath, "CIV4BuildInfos.xml")

		try:
			if(os.access(strSavePath,os.F_OK)):
				if(os.access(strFileSavePath,os.F_OK)):
					os.remove(strFileSavePath)
				os.removedirs(strSavePath)
		except:
			pass
			
		if(not os.access(strSavePath,os.F_OK)):
			os.makedirs(strSavePath)

							
		szText = "<?xml version=\"1.0\"?>"
		szText = appendString(szText,"<!-- Created by Tech Civilizeditor %s by TheLopez-->" %(editorVersion()))
		szText = appendString(szText,"<!-- Sid Meier's Civilization 4 -->")
		szText = appendString(szText,"<!-- Copyright Firaxis Games 2005 -->")
		szText = appendString(szText,"<!-- -->")
		szText = appendString(szText,"<!-- Build Infos -->")
		szText = appendString(szText,"<Civ4BuildInfos xmlns=\"x-schema:CIV4UnitSchema.xml\">")
		szText = appendString(szText,"	<BuildInfos>")
				
		for iBuild in range(gc.getNumBuildInfos()):

			if(gc.getBuildInfo(iBuild).isDeleted()):
				continue

			szText = appendString(szText,self.printBuild(iBuild))
			
						
		szText = appendString(szText,"	</BuildInfos>")
		szText = appendString(szText,"</Civ4BuildInfos>")

			
		fd = os.open(strFileSavePath, os.O_CREAT)
		os.close(fd)

		fd = os.open(strFileSavePath, os.O_RDWR)
		os.write(fd, szText)
		os.close(fd)
		
		if(g_bSaveChangesInEditorAssetsDirectory):
			strModAssetPath = "%s\%s" %(strModPath,"\Assets\XML\Units")
			strModAssetSavePath = "%s\%s" %(strModPath, "\Assets\XML\Units\CIV4BuildInfos.xml")
			try:
				if(os.access(strModAssetPath,os.F_OK)):
					if(os.access(strModAssetSavePath,os.F_OK)):
						os.remove(strModAssetSavePath)
			except:
				pass
			
			if(not os.access(strModAssetPath,os.F_OK)):
				os.makedirs(strModAssetPath)

			fd = os.open(strModAssetSavePath, os.O_CREAT)
			os.close(fd)

			fd = os.open(strModAssetSavePath, os.O_RDWR)
			os.write(fd, szText)
			os.close(fd)
	

